package com.sdry.web.controller.workplace;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hacker.base.BaseController;
import com.sdry.model.hpf.Bom;
import com.sdry.model.hpf.LineSideLibrary;
import com.sdry.model.hpf.LineSideLibraryOut;
import com.sdry.model.hpf.Part;
import com.sdry.model.hpf.Product;
import com.sdry.model.llm.Team;
import com.sdry.model.llm.User;
import com.sdry.model.workplace.Assemble;
import com.sdry.model.workplace.AssembleExample;
import com.sdry.model.workplace.AssembleExample.Criteria;
import com.sdry.service.hpf.BomService;
import com.sdry.service.hpf.LineSideLibraryService;
import com.sdry.service.hpf.PartService;
import com.sdry.service.hpf.ProductService;
import com.sdry.service.workplace.AssembleServise;
import com.sdry.service.workplace.OthersService;
import com.sdry.utils.ResponseUtil;
import com.sdry.utils.StringUtil;


/**
 * @ClassName: assembleController
 * @Description: 组装
 * @author tdd
 * @date 2018年8月29日
 * @version V1.0
 */
@Controller
@RequestMapping("/assemble")
public class AssembleController extends BaseController{

    @Resource
    private AssembleServise assembleServise;
    @Resource
    private OthersService othersService;
    //产品
  	@Resource
    private ProductService productServise;
  	//BOM
  	@Resource
    private BomService bomServise;
  	//线边库
  	@Resource
    private LineSideLibraryService lineSideLibraryService;
  	//配件
  	@Resource
    private PartService partService;
  	
    /**
     * 添加组装
     * @param response 响应
     * @param assemble 组装实体
     * @throws Exception 异常
     */
    @RequestMapping("/insertassemble")
    public void insertassemble(HttpServletRequest request, HttpServletResponse response, Assemble assemble) throws Exception {

        int affact = 0;

        AssembleExample example = new AssembleExample();
        Criteria createCriteria =  example.createCriteria();
        //名称查询
        if(assemble.getAtube() != null && assemble.getAtube() != "") {
            createCriteria.andAtubeEqualTo(assemble.getAtube());
        }
        createCriteria.andAremark1EqualTo("0");
        List<Assemble> assembles = assembleServise.selectByExample(example);
        if(assembles.size() == 0){
        	//判断session
      		HttpSession session = request.getSession();
      		// 从session中取出用户身份信息
      		User use = (User) session.getAttribute("currentUser");
      		//当前时间
            SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
            String   date   =   sDateFormat.format(new Date());
            assemble.setAoperator(use.getUserName());
            //操作人id
            assemble.setAremark2(String.valueOf(use.getUid()));
            assemble.setAremark5(use.getRemark3());
            //班组id
            Team team = (Team) session.getAttribute("team");
            assemble.setAremark3(String.valueOf(team.getTid()));
            //班次
            assemble.setAremark4(team.getCrew());
            assemble.setAtime(date);
        	assemble.setAremark("0");
        	//添加
            affact = assembleServise.insertSelective(assemble);
        }
        ResponseUtil.write(response, affact);
    }
    /**
     * 添加组装
     * @param response 响应
     * @param assemble 组装实体
     * @throws Exception 异常
     */
    @RequestMapping("/plInsertAssemble")
    public void plInsertAssemble(HttpServletRequest req, HttpServletResponse response, Assemble assemble) throws Exception {
    	String[] listM = req.getParameterValues("listM[]");
    	
    	//判断session
  		HttpSession session = req.getSession();
  		// 从session中取出用户身份信息
  		User use = (User) session.getAttribute("currentUser");
  		//当前时间
        SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        String   date   =   sDateFormat.format(new Date());
        assemble.setAoperator(use.getUserName());
        //操作人id
        assemble.setAremark2(String.valueOf(use.getUid()));
        assemble.setAremark5(use.getRemark3());
        //班组id
        Team team = (Team) session.getAttribute("team");
        assemble.setAremark3(String.valueOf(team.getTid()));
        //班次
        assemble.setAremark4(team.getCrew());
        assemble.setAtime(date);
    	assemble.setAremark("0");
    	
    	int affact = 0;
    	for (int i = 0; i < listM.length; i++) {
    		assemble.setMbcode(listM[i]);
    		//添加
    		affact = affact + assembleServise.insertSelective(assemble);
		}
    	ResponseUtil.write(response, affact);
    }

    /**
     * 带条件的分页查询组装信息
     * @param request 请求
     * @param response 响应
     * @param rows 每页记录数
     * @param page 页数
     * @param assemble 组装信息实体
     * @throws Exception 异常
     */
    @RequestMapping("/selectassembleList")
    public void selectassembleList(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "page",required = false)int page,
                                   @RequestParam(value = "rows",required = false)int rows,
                                   Assemble assemble) throws Exception {

    	PageHelper.startPage(page, rows);

        AssembleExample example = new AssembleExample();
        Criteria createCriteria =  example.createCriteria();
    	//名称模糊
        if(assemble.getAtube() != null && assemble.getAtube() != "") {
    		createCriteria.andAtubeLike("%"+assemble.getAtube()+"%");
    	}
        createCriteria.andAremarkEqualTo("0");
		List<Assemble> list = assembleServise.selectByExample(example);
		
		PageInfo<Assemble> info = new PageInfo<Assemble>(list);
    	
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("total", info.getTotal());
        jsonObject.put("rows", info.getList());
        ResponseUtil.write(response, jsonObject);
    }

    /**
     * 根据条件查询组装信息
     * @param response 响应
     * @param assemble 条件
     * @throws Exception 异常
     */
    @RequestMapping("/selectassembleByExample")
    public void selectassembleByExample(HttpServletResponse response, Assemble assemble) throws Exception {
        AssembleExample example = new AssembleExample();
        Criteria createCriteria =  example.createCriteria();
        //名称查询
        if(assemble.getAtube() != null && assemble.getAtube() != "") {
            createCriteria.andAtubeEqualTo(assemble.getAtube());
        }
        if(assemble.getMbcode() != null && assemble.getMbcode() != "") {
        	createCriteria.andMbcodeEqualTo(assemble.getMbcode());
        }
        createCriteria.andAremarkEqualTo("0");
        List<Assemble> assembles = assembleServise.selectByExample(example);
        //将对象转化为json数组
        JSONArray json = JSONArray.fromObject(assembles);
        ResponseUtil.write(response, json);
    }
    /**
     * 根据当前日期产品查询组装信息
     * @param response 响应
     * @param product 产品
     * @throws Exception 异常
     */
    @RequestMapping("/selectNumByDateAndProduct")
    public void selectNumByDateAndProduct(HttpServletRequest request,String product,HttpServletResponse response) throws Exception {
    	
    	//判断session
  		HttpSession session = request.getSession();
  		// 从session中取出用户身份信息
  		User use = (User) session.getAttribute("currentUser");
  		String date = use.getRemark3();
    	Map<String, Object> map = new HashMap<>();
		map.put("atube", "");
		map.put("atime", "");
		map.put("aremark5", date);
		map.put("product", product);
		//是否删除
		map.put("aremark", "");
		List<Assemble> assems = othersService.selectAtubeByDateAndProduct(map);
		int num  = assems.size();
    	ResponseUtil.write(response, num);
    }
    /**
     * 根据当前年度产品查询组装信息
     * @param response 响应
     * @param product 产品
     * @throws Exception 异常
     */
    @RequestMapping("/selectNumByYearAndProduct")
    public void selectNumByYearAndProduct(HttpServletRequest request,String product,HttpServletResponse response) throws Exception {
    	
    	//判断session
  		HttpSession session = request.getSession();
  		// 从session中取出用户身份信息
  		User use = (User) session.getAttribute("currentUser");
  		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  		SimpleDateFormat format = new SimpleDateFormat("yyyy");
  		String date = format.format(dateFormat.parse(use.getRemark3()));
  		
    	Map<String, Object> map = new HashMap<>();
		map.put("atube", "");
		map.put("atime", "");
		map.put("aremark5", date);
		map.put("product", product);
		//是否删除
		map.put("aremark", "");
		List<Assemble> assems = othersService.selectAtubeByDateAndProduct(map);
		int num  = assems.size();
    	ResponseUtil.write(response, num);
    }
    /**
     * 根据id查询组装信息
     * @param response 响应
     * @param id 组装id
     * @throws Exception 异常
     */
    @RequestMapping("/selectassembleById")
    public void selectassembleById(HttpServletResponse response, Long id) throws Exception {

        Assemble assemble = assembleServise.selectByPrimaryKey(id);
        //将对象转化为json
        JSONObject json = JSONObject.fromObject(assemble);
        ResponseUtil.write(response, json);
    }

    /**
     * 修改组装信息
     * @param response 响应
     * @param assemble 组装信息
     * @throws Exception 异常
     */
    @RequestMapping("/editassemble")
    public void editassemble( HttpServletResponse response,
                              Assemble assemble) throws Exception {

        int affct = 0;

        AssembleExample example = new AssembleExample();
        Criteria createCriteria =  example.createCriteria();
        //名称查询
        if(assemble.getAtube() != null && assemble.getAtube() != "") {
            createCriteria.andAtubeEqualTo(assemble.getAtube());
        }
        List<Assemble> assembles = assembleServise.selectByExample(example);
        if(assembles.size() == 0){
            //修改
            affct = assembleServise.updateByPrimaryKeySelective(assemble);
        }else if(assembles.size() == 1 && assembles.get(0).getAid().equals(assemble.getAid())){
            affct = assembleServise.updateByPrimaryKeySelective(assemble);
        }
        ResponseUtil.write(response, affct);
    }

    /**
     * 批量删除
     * @param response 响应
     * @param ids 组装id
     * @throws Exception 异常
     */
    @RequestMapping("/deleteassemble")
    public void deleteassemble( HttpServletResponse response, String ids) throws Exception {
    	List<Long> splitListL = StringUtil.splitListL(ids, ",");
	   	 int affact = 0;
	   	 for (int i = 0; i < splitListL.size(); i++) {
	   		 Assemble assemble = new  Assemble();
	   		 assemble.setAid(splitListL.get(i));
	   		 assemble.setAremark("1");
	   		affact += assembleServise.updateByPrimaryKeySelective(assemble);
		 }
        //int affact = assembleServise.deleteByPrimaryKeys(ids);
	   	 
	   //线边库入库
	   	 Long aid = splitListL.get(0);
	   	Assemble assemble = assembleServise.selectByPrimaryKey(aid);
 		//1、根据产品条码判定编码规则
 		String productNumber = "";
 		String atube = assemble.getAtube().substring(3, 7);
 		if("0960".equals(atube)){
 			productNumber = "PSH2-0960-T-01";
 		}else if("0980".equals(atube)){
 			productNumber = "PSH2-0980-T-02";
 		}else if("1080".equals(atube)){
 			productNumber = "PSH1-1080-C-04";
 		}else if("1060".equals(atube)){
 			productNumber = "PSH1-1060-B-03";
 		}
 		//2、找到对应的BOM值
 		List<Product> list = productServise.getProductByNumber(productNumber);
 		Product product = list.get(0);
 		List<Bom> bomList = bomServise.getBomByPid(product.getPid());
 		//3、调用线边库入库的方法
 		for(Bom bom : bomList){
 			Part part = partService.getPartByPaid(bom.getPaid());
 			if("组装".equals(part.getParemark4())){
 				LineSideLibraryOut lineSideLibraryOut = lineSideLibraryService.findLineSideLibraryOutByPaID(bom.getPaid());
 				if(lineSideLibraryOut != null){
 					lineSideLibraryService.twoInsert(bom.getPaid(), lineSideLibraryOut.getBatch(), bom.getNumber(), assemble.getAplan());
 				}
 			}
 		}
 		
        ResponseUtil.write(response, affact);
    }

    /**
     * 批量修改
     * @param response 响应
     * @param assemble 组装
     * @throws Exception 异常
     */
    @RequestMapping("/updateassembles")
    public void updateassembles( HttpServletResponse response, Assemble assemble) throws Exception {
    	 AssembleExample example = new AssembleExample();
         Criteria createCriteria =  example.createCriteria();
         //名称查询
         if(assemble.getAtube() != null && assemble.getAtube() != "") {
             createCriteria.andAtubeEqualTo(assemble.getAtube());
         }
         if(assemble.getMbcode() != null && assemble.getMbcode() != "") {
         	createCriteria.andMbcodeEqualTo(assemble.getMbcode());
         }
         createCriteria.andAremarkEqualTo("0");
    	Assemble record = new  Assemble();
		assemble.setAremark("1");
    	int affact = assembleServise.updateByExampleSelective(record, example);
    	ResponseUtil.write(response, affact);
    }
}
